#include "texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

mray::BitmapTexture::BitmapTexture(const std::string& file){
	data = stbi_load(file.c_str(), &w, &h, &n ,0); 
	//process data
	int row_size = w * 3;
	unsigned char* buffer = new unsigned char[row_size];
	for(int i = 0, j = h-1; i <= j; i++, j--){
		memcpy(buffer, data+row_size*i, row_size);
		memcpy(data+row_size*i, data+row_size*j, row_size);
		memcpy(data+row_size*j, buffer, row_size);
	}
	delete [] buffer;
}

mray::vec3 mray::BitmapTexture::GetColor(const vec2& uv) const
{
	int uu = (int)(uv.u * w);
	int vv = (int)(uv.v * h);
	int lo = (vv * w + uu)*3;

	float r = uchar2float(data[lo]);
	float g = uchar2float(data[lo+1]);
	float b = uchar2float(data[lo+2]);
	return vec3(r, g, b);
}